package org.tsinghua.vaccine.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tsinghua.vaccine.entity.Circulation;
import org.tsinghua.vaccine.entity.Inoculation;
import org.tsinghua.vaccine.entity.Vaccine;
import org.tsinghua.vaccine.repository.VaccineRepository;

/**
 * @author ipenta
 * @ClassName: VaccineService
 * @Description: TODO
 * @date 2017-09-20 下午3:01
 */
@Service
public class VaccineService {

	@Autowired
	VaccineRepository vaccineRepository;


	public Vaccine recordCirculation(Vaccine vaccine, Circulation circulation) {

		if (recordToBlockChain()) {
			return  recordCirculationToLocal(vaccine, circulation);
		}

		return null;
	}

	public Vaccine recordInoculation(String vaccineId, Inoculation inoculation) {

		if (recordToBlockChain()) {
			return recordInoculationToLocal(vaccineId, inoculation);
		}

		return null;
	}

	public Boolean recordToBlockChain() {
		//TODO 写入区块链
		return Boolean.TRUE;
	}

	public Vaccine recordCirculationToLocal(Vaccine vaccine, Circulation circulation) {
		Vaccine entity = vaccineRepository.findOne(vaccine.getId());

		if (null != entity){
			entity.getCirculations().add(circulation);
			vaccineRepository.save(entity);
			return  entity;
		}else {
			vaccine.getCirculations().add(circulation);
			vaccineRepository.save(vaccine);
			return vaccine;
		}
	}

	public Vaccine recordInoculationToLocal(String vaccineId, Inoculation inoculation) {
		Vaccine entity = vaccineRepository.findOne(vaccineId);

		if (null != entity){
			entity.getInoculations().add(inoculation);
			vaccineRepository.save(entity);
			return  entity;
		}
		return null;
	}

	public Vaccine findRecord(String vaccineId) {
		return vaccineRepository.findOne(vaccineId);
	}
}
